
//#include "head.h"
//#include <stdio.h>
#include <signal.h>

#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpUtil.h>
#include <workflow/HttpMessage.h>
#include <workflow/RedisMessage.h>

using std::cout;
using std::endl;
using std::string;
using std::vector;

//初始化计数器的值为1
static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf(">> sig num %d is comming\n", num);
    //调用一次done方法，计数器的值减1
    waitGroup.done();
}

void process(WFHttpTask * serverTask)
{
    //只要执行process函数，一定接收到了对端的请求数据
    printf("process is running.\n");
    //0. 对任务的状态进行检测
    //...
    //1. 解析请求
    auto req = serverTask->get_req();
    string uri = req->get_request_uri();
    cout << "uri: " << uri << endl;

    protocol::HttpHeaderCursor cursor(req);
    string value;
    if(cursor.find("Host", value)) {
        cout << "Host: " <<  value << endl;
    }

    //解析用户名和密码
    string usernameKV = uri.substr(0, uri.find("&"));
    string passwordKV = uri.substr(uri.find("&") + 1);
    string username = usernameKV.substr(usernameKV.find("=") + 1);
    string password = passwordKV.substr(passwordKV.find("=") + 1);
    cout << "username: " << username << endl;
    cout << "password: " << password << endl;

    //2. 访问Redis，并进行验证
    string url = "redis://127.0.0.1:6379";
    auto redisTask = WFTaskFactory::create_redis_task(url, 1, 
    [serverTask, password](WFRedisTask * redistask){
        //....
        //0. 对任务的状态和错误进行检测
        //1. 获取响应信息
        protocol::RedisValue result;
        auto redisResp = redistask->get_resp();
        redisResp->get_result(result);
        if(result.is_string()) {
            string passwd = result.string_value();
            //与serverTask中解析出来的password进行对比
            if(password == passwd) {
                //验证通过的情况
                serverTask->get_resp()->append_output_body("Login Success!");
            } else {//验证失败的情况
                serverTask->get_resp()->append_output_body("Login Failed!");
            }
        } else {
            //不是字符串形式时，一定出错，生成响应信息
            serverTask->get_resp()->append_output_body("Login Failed!");
        }
    });
    string command("HGET");
    vector<string> params {"student", username};
    redisTask->get_req()->set_request(command, params);
    series_of(serverTask)->push_back(redisTask);
}

void test0()
{
    signal(SIGINT, sighandler);

    WFHttpServer httpServer(process);

    if(httpServer.start(8888) == 0) {
        //当调用wait方法会阻塞当前线程
        waitGroup.wait();
        httpServer.stop();
    } else {
        printf("Http Server start failed.\n");
    }
    cout << "\n>> test0 exit" << endl;
}


int main()
{
    test0();
    return 0;
}

